package com.zp.ojcodesandbox.util;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ListConfigsCmd;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.PullImageCmd;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerContextMetaFile;

import javax.print.Doc;
import java.util.HashMap;
import java.util.List;

public class InitEnvirment {
    private static boolean first_java;
    public static final String JAVA_IMAGE = "openjdk:8-alpine";
    public static final String CPP_IMAGE = "gcc:latest";

    static {
        first_java = true;
    }

    public static void main(String[] args) {
        // 删除容器
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containerList = listContainersCmd.withShowAll(true).exec();
        String image = "openjdk:8-alpine";
        for(Container container : containerList){
            if(container.getImage().equals(image) && !container.getStatus().contains("Up")){
                dockerClient.removeContainerCmd(container.getId()).withForce(true).exec();
                System.out.println(container);
            }
        }
//        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
//        exec(dockerClient);
    }

    public static void exec(DockerClient dockerClient){
        // 拉取java镜像
        if(first_java){
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(CPP_IMAGE);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item){
                    System.out.println("下载镜像: " + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("java下载失败");
                throw new RuntimeException(e);
            }
            System.out.println("java镜像下载完成");
            first_java = false;
        }
    }
}
